package com.situation.config;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.Serializable;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisSessionDao extends AbstractSessionDAO {

    @Autowired
    private RedisTemplate redisTemplate;

    private final long expire = 3600;

    @SneakyThrows
    @Override
    protected Serializable doCreate(Session session) {
        //生成id（使用uuid）
        Serializable sessionId = this.generateSessionId(session);
        //为会话指定唯一的id
        this.assignSessionId(session, sessionId);
        //将会话保存到redis
        redisTemplate.opsForValue().set(sessionId, session, expire, TimeUnit.SECONDS);
        return sessionId;
    }

    @SneakyThrows
    @Override
    protected Session doReadSession(Serializable serializable) {
        if (serializable == null) {
            return null;
        }
        Session session = (Session) redisTemplate.opsForValue().get(serializable);
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            return;
        }
        session.setTimeout(expire * 1000);
        redisTemplate.opsForValue().set(session.getId(), session, expire, TimeUnit.SECONDS);
    }

    @Override
    public void delete(Session session) {
        if (session == null || session.getId() == null) {
            return;
        }
        redisTemplate.delete(session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        return redisTemplate.keys("*");
    }
}
